package com.example.weatheringwithyou

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.weatheringwithyou.base.BaseBindingActivity
import com.example.weatheringwithyou.databinding.ActChangeAvatarBinding
import com.example.weatheringwithyou.storage.TokenPreferences
import com.example.weatheringwithyou.utils.AvatarUploader
import kotlinx.coroutines.launch

class ChangeAvatarActivity : BaseBindingActivity<ActChangeAvatarBinding>() {

    private val REQUEST_IMAGE_CAPTURE = 1
    private val REQUEST_IMAGE_PICK = 2

    // 头像地址
    private var avatarUrl: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setOnClickEvent()

        // 从Application获取头像地址
        avatarUrl = WeatherApplication.user.avatar
        loadAvatar(avatarUrl.toString())
    }

    private fun loadAvatar(url: String) {
        // 加一个协程
        lifecycleScope.launch {
            // 使用Glide加载图片
            Glide.with(this@ChangeAvatarActivity)
                .load(url)
                .apply(RequestOptions.circleCropTransform())
                .into(binding.ivAvatar)
        }
    }

    override fun initBinding(layoutInflater: LayoutInflater): ActChangeAvatarBinding {
        return ActChangeAvatarBinding.inflate(layoutInflater)
    }

    //设置点击事件
    fun setOnClickEvent() {
        binding.ivBack.setOnClickListener { finish() }
        binding.ivAvatar.setOnClickListener { showImagePickerDialog() }
        binding.ivEditAvatar.setOnClickListener { showImagePickerDialog() }
    }

    private fun showImagePickerDialog() {
        val options = arrayOf<CharSequence>("拍照", "从相册选择", "取消")
        val builder = android.app.AlertDialog.Builder(this)
        builder.setTitle("选择头像")
        builder.setItems(options) { dialog, item ->
            when {
                options[item] == "拍照" -> {
                    takePhoto()
                }

                options[item] == "从相册选择" -> {
                    pickFromGallery()
                }

                options[item] == "取消" -> {
                    dialog.dismiss()
                }
            }
        }
        builder.show()
    }

    //从相册选择
    @SuppressLint("IntentReset")
    private fun pickFromGallery() {
        // 创建一个意图来选择图片，指定动作是ACTION_PICK，并且数据来源为外部存储中的图片媒体
        val intent = Intent(
            Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        )
        // 设置MIME类型为图片类型，确保只有图片文件可以选择
        intent.type = "image/*"
        // 启动活动以获取结果，传入定义好的请求码REQUEST_IMAGE_PICK
        startActivityForResult(intent, REQUEST_IMAGE_PICK)
    }

    //拍照
    private fun takePhoto() {
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // 检查结果是否成功
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                // 如果是来自图片选择器的请求
                REQUEST_IMAGE_PICK -> {
                    // 使用安全调用操作符访问data对象的data属性（即URI），如果存在则执行lambda表达式
                    data?.data?.let { uri ->
                        // 将选中的图片通过URI设置到ivAvatar控件上显示出来
                        //binding.ivAvatar.setImageURI(uri)
                        uploadImage(uri)
                    }
                }
            }
        }
    }

    private fun uploadImage(uri: Uri) {
        // 开启一个协程
        lifecycleScope.launch {
            // 获取上下文
            val context = this@ChangeAvatarActivity
            val authToken = TokenPreferences.getInstance(context).getToken()
            AvatarUploader(context, authToken.toString()) { avatarUrl, error ->
                if (error != null) {
                    // 处理错误
                    Log.e("上传头像错误", error)
                } else {
                    loadAvatar(avatarUrl.toString())
                }
            }.uploadAvatar(uri)
        }
    }
}